package com.fare.taluo.application.impl.crawl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.application.crawl.ICrawlFreightPriceApplication;
import com.fare.taluo.application.plane.city.PortApplication;
import com.fare.taluo.core.domain.FlightPrice;
import com.fare.taluo.core.domain.entity.crawl.FreightPriceEntity;
import com.fare.taluo.vo.core.AgentEntityVO;
import com.fare.taluo.vo.core.CabinEntityVO;
import com.fare.taluo.vo.core.PlaneInfo;
import com.fare.taluo.vo.core.PortEntityVO;
import com.fare.taluo.vo.core.TransitchangeEntityVO;
import com.foreveross.crawl.common.util.DateUtil;
import com.foreveross.crawl.domain.freight.AgentEntity;
import com.foreveross.crawl.domain.freight.CabinEntity;
import com.foreveross.crawl.domain.freight.PlaneInfoEntity;
import com.foreveross.crawl.domain.freight.TransitchangeEntity;

@Service
@Transactional
public class CrawlFreightPriceApplicationImpl implements
		ICrawlFreightPriceApplication {

	private static final SimpleDateFormat SDF_DATE=new SimpleDateFormat("yyyy-MM-dd");
	private static final SimpleDateFormat SDF_TIME=new SimpleDateFormat("HH:mm");
	@Override
	public PlaneInfo crawlLowestPlaneInfoByCompany(String fromCode,
			String toCode, String flightDate, String[] flightTimes,
			String carrierKey,String flag) throws Exception {
		FlightPrice flightPrice =generateFlightPrice(fromCode, toCode, flightDate, flightTimes, carrierKey,flag);
		PlaneInfoEntity e=flightPrice.crawlLowestPlaneInfoByCompany();
		PlaneInfo vo = null;
		//转换为vo视图对象
		if(e!=null){
			vo=buildPlaneInfo(e);
		}
		return vo;
	}


	@Override
	public List<PlaneInfo> crawlAllPlaneInfosByCompany(String depCity,
			String arrCity, String flightDate, String[] flightTimes,
			String carrierKey) throws Exception {
		List<PlaneInfo> finalResult=new  ArrayList<PlaneInfo>();
		FlightPrice flightPrice=generateFlightPrice(depCity,arrCity,flightDate,flightTimes,carrierKey,null);
		List<PlaneInfoEntity> ps=flightPrice.crawlAllPlaneInfosByCompany();
		for(PlaneInfoEntity p:ps){
			if(p!=null){
				
				finalResult.add(buildPlaneInfo(p));
			}
		}
		
		
		
		
		
		List<PlaneInfo> planeList = null;
		Map<String,List<CabinEntityVO>> map = new HashMap<String, List<CabinEntityVO>>();
		FreightPriceEntity entity = new FreightPriceEntity();
		planeList = finalResult;
		//对仓位重新组织，将cabin_type一样的仓位归类
		for (PlaneInfo planeInfo : planeList) {
			List<CabinEntityVO> cabins = planeInfo.getCabins();
			if(cabins != null && cabins.size()>0){
				for (CabinEntityVO cabinEntityVO : cabins) {
					if(map.containsKey(cabinEntityVO.getCabinType())){
						map.get(cabinEntityVO.getCabinType()).add(cabinEntityVO);
					}else{
						List<CabinEntityVO> putList = new ArrayList<CabinEntityVO>();
						putList.add(cabinEntityVO);
						map.put(cabinEntityVO.getCabinType(), putList);
					}
				}
			}
			
			//重新放到
			Set<Map.Entry<String, List<CabinEntityVO>>> set = map.entrySet();
	        for (Iterator<Map.Entry<String, List<CabinEntityVO>>> it = set.iterator(); it.hasNext();) {
	            Map.Entry<String, List<CabinEntityVO>> entry = (Map.Entry<String, List<CabinEntityVO>>) it.next();
	            //再将同类型的仓位按价格排序
	            List<CabinEntityVO> cabinList = entry.getValue();
	            Collections.sort(cabinList,new PriceComparator());
	            planeInfo.getClassifyCabins().add(cabinList);
                //  System.out.println(entry.getKey() + "--->" + entry.getValue());
	        }		
			map.clear();
		}
		
		
		return planeList;
		///return finalResult;
	}
	/**
	 * 拼装一个领域对象出来
	 * @param depCity
	 * @param arrCity
	 * @param flightDate
	 * @param flightTimes
	 * @param carrierKey
	 * @return
	 */
	private FlightPrice generateFlightPrice(String depCity,String arrCity,String flightDate,String[] flightTimes,String carrierKey,String flag){
		//传入的是城市名称，需要先查询一次
		PortApplication portApplication = InstanceFactory.getInstance(PortApplication.class);
		PortEntityVO fromPort = portApplication.findPortEntityByCityName(depCity.trim());
		PortEntityVO toPort = portApplication.findPortEntityByCityName(arrCity.trim());
		//组装抓取条件
		FlightPrice flightPrice = new FlightPrice();
		flightPrice.setAreaCode(fromPort.getAreaCode());
		flightPrice.setAreaName(fromPort.getAreaName());
		flightPrice.setFromCity(fromPort.getPortCode());
		flightPrice.setFromCityName(depCity);
		flightPrice.setToCity(toPort.getPortCode());
		flightPrice.setToCityName(arrCity);
		flightPrice.setFlightDate(flightDate);
		flightPrice.setFlightTimes(flightTimes);
		flightPrice.setCarrierKey(carrierKey);
		flightPrice.setFlag(flag);
		return flightPrice;
	}
	/**
	 * 生成一个planeInfo
	 * @param carrierKey
	 * @param carrierName
	 * @param carrierFullName
	 * @param fromCity
	 * @param fromCityName
	 * @param toCity
	 * @param toCityName
	 * @param flightNo
	 * @param type
	 * @param areaCode
	 * @param areaName
	 * @param lowerPrice
	 * @param highPrice
	 * @param lowerAgentName
	 * @param flightBatchDate
	 * @param flightBatchStartTime
	 * @param flightBatchEndTime
	 * @param agents
	 * @param cabins
	 * @param transit
	 * @param createTime
	 * @return
	 * @throws Exception 
	 */
	private PlaneInfo buildPlaneInfo(PlaneInfoEntity e) throws Exception{
		PlaneInfo p=new PlaneInfo();
		p.setCarrierKey(e.getCarrierKey());
		p.setCarrierName(e.getCarrierName());
		p.setCarrierFullName(e.getCarrierFullName());
		p.setFromCity(e.getFromCity());
		p.setFromCityName(e.getFromCityName());
		p.setToCity(e.getToCity());
		p.setToCityName(e.getToCityName());
		p.setFlightId(e.getFlightNo());
		p.setGrapDate(new Date());
		p.setGrabDate(DateUtil.formatDay(new Date(), "yyyyMMddHHmmssSSS"));
		p.setType(e.getType());
		p.setAreaCode(e.getAreaCode());
		p.setAreaName(e.getAreaName());
		p.setLowerPrice(e.getLowerPrice()==null?"":e.getLowerPrice().toString());
		p.setHighPrice(e.getHighPrice()==null?"":e.getHighPrice().toString());
		p.setAgentName(e.getAgentName());
		p.setFlightBatchDate(e.getFlightDate());
		try {
			p.setFlightBatchStartTime(SDF_TIME.format(e.getStartTime()));
			p.setFlightBatchEndTime(SDF_TIME.format(e.getEndTime()));
		} catch (Exception e1) {}
		p.setAgents(buildAgentInfos(e.getAgents()));
		p.setCabins(buildCabinEntityVOs(e.getCabins()));
		p.setTransit(buildTransitchangeEntityVOs(e.getTransit()));
		return p;
	}
	
	private List<AgentEntityVO> buildAgentInfos(Set<AgentEntity> as){
		List<AgentEntityVO> finalResult=new ArrayList<AgentEntityVO>();
		Iterator<AgentEntity> i=as.iterator();
		while(i.hasNext()){
			AgentEntity ae=(AgentEntity)i.next();
			finalResult.add(buildAgentInfo(ae));
		}
		return finalResult;
	}
	
	private AgentEntityVO buildAgentInfo(AgentEntity e){
		AgentEntityVO a=new AgentEntityVO();
		a.setName(e.getName());
		a.setCname(e.getName());
		a.setPrice(e.getPrice().toString());
		return a;
	}
	
	private List<CabinEntityVO> buildCabinEntityVOs(Set<CabinEntity> cs){
		List<CabinEntityVO> finalResult=new ArrayList<CabinEntityVO>();
		Iterator<CabinEntity> i=cs.iterator();
		while(i.hasNext()){
			CabinEntity ce=(CabinEntity)i.next();
			finalResult.add(buildCabinEntityVO(ce));
		}
		return finalResult;
	}
	
	private CabinEntityVO buildCabinEntityVO(CabinEntity e){
		CabinEntityVO c=new CabinEntityVO();
		c.setCabinName(e.getCabinName());
		c.setCabinNo(e.getCabinNo());
		c.setCabinRebate(e.getCabinRebate());
		c.setCabinServer(e.getCabinServer());
		c.setCabinType(e.getCabinType());
		c.setLever(String.valueOf(e.getLevel()));
		
		try {
			String price = e.getPrice();
			if(price.contains("￥")){
				price = price.replace("￥", "");
			}
			c.setPrice(Double.valueOf(price));
		} catch (NumberFormatException e1) {}
		return c;
	}
	
	private List<TransitchangeEntityVO> buildTransitchangeEntityVOs(List<TransitchangeEntity> es)throws Exception{
		List<TransitchangeEntityVO> finalResult=new ArrayList<TransitchangeEntityVO>();
		for(TransitchangeEntity e:es){
			finalResult.add(buildTransitchangeEntityVO(e));
		}
		return finalResult;
	}
	private TransitchangeEntityVO buildTransitchangeEntityVO(TransitchangeEntity e) throws Exception{
		TransitchangeEntityVO vo=new TransitchangeEntityVO();
		vo.setTransitCarrierKey(e.getCarrierKey());
		vo.setTransitName(e.getCarrierName());
		vo.setTransitFullName(e.getCarrierFullName());
//		vo.setFlightNo(e.getFlightNo());
//		vo.setFromCity(e.getFromCity());
//		vo.setFromCityCode(e.getFromCityCode());
//		vo.setToCity(e.getToCity());
//		vo.setToCityCode(e.getToCityCode());
//		vo.setFlightTime(e.getFlightTime());
		BeanUtils.copyProperties(vo, e);
		return vo;
	}

	class PriceComparator implements Comparator<CabinEntityVO>{

		@Override
		public int compare(CabinEntityVO cabin1, CabinEntityVO cabin2) {
			double price1 = cabin1.getPrice();
			double price2 = cabin2.getPrice();
			if(price1 > price2){
				return -1;
			}else if(price1 < price2){
				return 1;
			}else {
				return 0;
			}		
		}
		
	}
	
}
